import 'dart:io';
import 'dart:ui' as ui show Image;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/view/component/MessagePaneBackgroundView.dart';

import '../../../../pojo/ImPojo.dart';
import '../../../../util/FileUtil.dart';
import '../../../../util/ImConstant.dart';
import '../../../../util/ImageUtil.dart';
import '../../../../util/MessageUtil.dart';
import '../../../bloc/ImagePageCubit.dart';
import '../../../bloc/MessageListCubit.dart';
import '../../../bloc/MessageSendCubit.dart';
import '../../../ext/MessageSelectionControls.dart';
import '../../../sub/ImagePage.dart';
import '../UiUtil.dart';
import 'MessagePane.dart';

class ImageMessagePane extends StatelessWidget {
  final WrapImMessage wrapMessage;

  const ImageMessagePane({required this.wrapMessage, super.key});

  @override
  Widget build(BuildContext context) {
    if (wrapMessage.message.messageType != ImMessageType.Image) {
      throw Exception("消息类型不对 ${wrapMessage.message.messageType.name}");
    }
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: buildBody(context),
    );

    // if (wrapMessage.message.currentUserId == wrapMessage.message.fromUserId) {
    //   // 发送者
    //   return Padding(
    //     padding: const EdgeInsets.only(left: 10, right: 10),
    //     child: buildBody(context),
    //   );
    // } else {
    //   // 接受者
    //   if (wrapMessage.message.fileStatus == ImMessageFileStatus.downloaded) {
    //     return Padding(
    //       padding: const EdgeInsets.only(left: 10, right: 10),
    //       child: buildBody(context),
    //     );
    //   } else if (wrapMessage.message.fileStatus == ImMessageFileStatus.empty) {
    //     return MessagePaneBackgroundView(message: wrapMessage.message, child: const Text('图片正在上传中'));
    //   } else if (wrapMessage.status == WrapImMessageStatus.downloading) {
    //     return MessagePaneBackgroundView(message: wrapMessage.message, child: const Text('图片正在下载中'));
    //   } else if (wrapMessage.status == WrapImMessageStatus.no_download) {
    //     return MessagePaneBackgroundView(message: wrapMessage.message, child: const Text('图片正在上传中'));
    //   } else {
    //     return MessagePaneBackgroundView(message: wrapMessage.message, child: Text('不应该出现${wrapMessage.status}'));
    //   }
    // }
  }

  Widget buildBody(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    var messageListCubit = context.read<MessageListCubit>();
    var imagePath = MessageUtil.getFilePath2(wrapMessage.message);
    var isExisted = FileUtil.fileExisted(imagePath);
    if (!isExisted) {
      return buildSvgView('assets/svg/image.svg', 80, 60, Colors.black54);
    }
    int imageWidth = wrapMessage.message.messageExt?.imageWidth??ImConstant.MESSAGE_IMAGE_FIT_MAX_WIDTH;
    int imageHeight = wrapMessage.message.messageExt?.imageHeight??ImConstant.MESSAGE_IMAGE_FIT_MAX_HEGITH;

    double fitWidth = ImageUtil.calcFitImageWidth(ImConstant.MESSAGE_IMAGE_FIT_MAX_WIDTH, imageWidth, imageHeight);
    double fitHeight = ImageUtil.calcFitImageHeight(fitWidth, imageWidth, imageHeight);
    return SelectableText.rich(
        TextSpan(
          children: [
            WidgetSpan(
                child: Container(
              width: fitWidth,
              height: fitHeight,
              decoration:  BoxDecoration(
                color: Colors.transparent,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.5, red: 0, blue: 0, green: 0), // 阴影颜色
                    spreadRadius: 0, // 阴影扩展半径
                    blurRadius: 10, // 阴影模糊半径
                    offset: const Offset(0, 2), // 阴影偏移量
                  ),
                ],
              ),
              child: GestureDetector(
                onTap: () async {
                  // List<int> sizes = await ImageUtil.getImageSize(imagePath);
                  if (context.mounted) {
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return BlocProvider(
                        create: (context) => ImagePageCubit(),
                        child: ImagePage(
                          imagePath: imagePath,
                          imageHeight: imageHeight,
                          imageWidth: imageWidth,
                          messageId: wrapMessage.message.id!,
                        ),
                      );
                    }));
                  }
                },
                child: buildImageHero(imagePath),
              ),
            ))
          ],
        ),
        selectionControls: MessageSelectionControls(
            message: wrapMessage.message, messageSendCubit: messageSendCubit, messageListCubit: messageListCubit));
  }

  Widget buildImageHero(String imagePath) {
    return Hero(
      tag: "messageImage_${wrapMessage.message.id}",
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: Image(image: FileImage(File(imagePath)!), fit: BoxFit.fitWidth),
      ),
    );
  }
}

class ImageMessageRefPane extends StatelessWidget {
  final ImMessage message;
  final MessageRefParam param;

  const ImageMessageRefPane({required this.message, required this.param, super.key});

  @override
  Widget build(BuildContext context) {
    if (message.messageType != ImMessageType.Image) {
      throw Exception("消息类型不对 ${message.messageType.name}");
    }
    if (message.currentUserId == message.fromUserId) {
      // 发送者
      return buildBody(context);
    } else {
      // 接受者
      if (message.fileStatus == ImMessageFileStatus.downloaded) {
        return buildBody(context);
      } else if (message.fileStatus == ImMessageFileStatus.empty) {
        return MessagePaneBackgroundView(message: message, child: const Text('图片正在上传中'));
      } else if (message.fileStatus == ImMessageFileStatus.downloading) {
        return MessagePaneBackgroundView(message: message, child: const Text('图片正在下载中'));
      } else if (message.fileStatus == ImMessageFileStatus.none) {
        return MessagePaneBackgroundView(message: message, child: const Text('可以下载图片'));
      } else {
        return MessagePaneBackgroundView(message: message, child: Text('不应该出现${message.fileStatus}'));
      }
    }
  }

  Widget buildBody(BuildContext context) {
    var imagePath = MessageUtil.getFilePath2(message);
    return GestureDetector(
        onTap: () async {
          List<int> sizes = await ImageUtil.getImageSize(imagePath);
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return BlocProvider(
              create: (context) => ImagePageCubit(),
              child: ImagePage(
                imagePath: imagePath,
                imageHeight: sizes[1],
                imageWidth: sizes[0],
                messageId: message.id!,
              ),
            );
          }));
        },
        child: SelectableText.rich(TextSpan(
          children: [
            WidgetSpan(
                child: Container(
              constraints: BoxConstraints(maxWidth: param.refMaxLength, maxHeight: 150),
              // margin: const EdgeInsets.only(left: 5, right: 5),
              child: buildImageHero(imagePath),
            ))
          ],
        )));
  }

  Widget buildImageHero(String imagePath) {
    return Image(image: FileImage(File(imagePath)!), fit: BoxFit.fitWidth);
  }
}
